
package com.zcp.notepad;

import com.zcp.notepad.NotePad.Notes;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SelectList extends ListActivity {
    private Button done;

    private String doneText;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.select_list);

        Intent intent = getIntent();
        if (intent.getData() == null) {
            intent.setData(Notes.CONTENT_URI);
        }
        doneText = getString(R.string.done);
        setTitle();
        initializeList();
        setListData();
        initializeButton();
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {

        super.onListItemClick(l, v, position, id);
        ViewHolder vh = (ViewHolder) v.getTag();
        CheckBox checkBox = vh.select;
        checkBox.setChecked(!checkBox.isChecked());
    }

    /**
     * 获取选中数据副本。
     * 
     * @return
     */
    protected ArrayList<HashMap<String, Object>> getCheckObject() {
        ArrayList<HashMap<String, Object>> checkObject = new ArrayList<HashMap<String, Object>>();
        if (data != null) {
            for (HashMap<String, Object> d : data) {
                if ((Boolean.valueOf(d.get("check").toString()))) {
                    checkObject.add((HashMap<String, Object>) d.clone());
                }
            }
        }
        return checkObject;
    }

    /**
     * 删除选中的项。
     * 
     * @return
     */
    protected void deleteSelect() {
        StringBuilder buffer = new StringBuilder();
        buffer.append(Notes._ID + " in(");
        boolean isHave = false;
        ArrayList<HashMap<String, Object>> wantDelete = new ArrayList<HashMap<String, Object>>();
        for (HashMap<String, Object> d : data) {
            if ((Boolean.valueOf(d.get("check").toString()))) {
                buffer.append(d.get(PROJECTION[0]) + ",");
                isHave = true;
                wantDelete.add(d);
            }
        }
        buffer.delete(buffer.length() - 1, buffer.length());
        buffer.append(")");
        if (isHave) {
            getContentResolver().delete(Notes.CONTENT_URI, buffer.toString(), null);
            for (HashMap<String, Object> d : wantDelete) {
                data.remove(d);
                Util.deleteShortcutToOptions(this, String.valueOf(d.get(Notes.TITLE)), Integer
                        .valueOf(d.get(Notes._ID).toString()).intValue());
                Util.cancelAlarmSet(this, d.get(Notes._ID).toString());
            }
            adapter.notifyDataSetChanged();
            checkSelectAll();
        }
    }

    /**
     * 处理设置的标题
     */
    protected void setTitle() {
        // 子类实现
    }

    /**
     * 处理done按钮点击事件
     */
    protected void dealDoneOnClick() {
        // 子类实现
    }

    /**
     * 处理cancel按钮点击实现。
     */
    protected void dealCancelOnClick() {

    }

    private void initializeButton() {
        done = (Button) findViewById(R.id.Done);
        done.setEnabled(false);
        Button cancel = (Button) findViewById(R.id.Cancel);
        selectAll = (CheckBox) findViewById(R.id.selectAll);
        selectAll.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                boolean isChecked = selectAll.isChecked();
                if (isChecked) {
                    for (HashMap<String, Object> d : data) {
                        d.put("check", true);
                    }
                    adapter.notifyDataSetChanged();
                } else {
                    for (HashMap<String, Object> d : data) {
                        d.put("check", false);
                    }
                    adapter.notifyDataSetChanged();
                }
            }

        });

        done.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dealDoneOnClick();

            }
        });
        cancel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                dealCancelOnClick();
            }
        });

    }

    /**
     * 初始化list
     */
    private void initializeList() {
        data = new ArrayList<HashMap<String, Object>>();
        adapter = new MyAdapter(this, data, R.layout.select_list_item, new String[] {
                PROJECTION[1], "check"
        }, new int[] {
                R.id.noteValue, R.id.check
        });
        setListAdapter(adapter);

    }

    /**
     * 设置list中的数据.
     */
    private void setListData() {
        data.clear();
        Cursor cursor = managedQuery(getIntent().getData(), PROJECTION, null, null,
                Notes.DEFAULT_SORT_ORDER);
        if ((cursor != null) && (cursor.moveToFirst())) {
            int idIndex = cursor.getColumnIndex(PROJECTION[0]);
            int titleIndex = cursor.getColumnIndex(PROJECTION[1]);
            int colorIndex = cursor.getColumnIndex(PROJECTION[3]);
            int lockIndex = cursor.getColumnIndex(PROJECTION[4]);
            HashMap<String, Object> item = null;
            do {
                item = new HashMap<String, Object>();
                item.put(PROJECTION[0], cursor.getInt(idIndex));
                item.put(PROJECTION[1], cursor.getString(titleIndex));
                item.put("check", false);
                item.put(PROJECTION[4], cursor.getInt(lockIndex));
                item.put(PROJECTION[3], cursor.getString(colorIndex));
                data.add(item);
            } while (cursor.moveToNext());
        }
    }

    private void checkSelectAll() {
        String text = doneText;
        if (data != null) {
            boolean isAllCheck = true;
            done.setEnabled(false);
            int count = 0;
            for (HashMap<String, Object> d : data) {
                if ((Boolean.valueOf(d.get("check").toString()))) {
                    done.setEnabled(true);
                    count++;
                } else {
                    isAllCheck = false;
                }
            }
            if (data.size() == 0) {
                isAllCheck = false;
                done.setEnabled(false);
            }
            selectAll.setChecked(isAllCheck);
            if (count > 0) {
                text = text + "(" + count + ")";
            }
        }

        done.setText(text);

    }

    /****************************************************************************************************************************************/

    class ViewHolder {
        TextView noteValue;

        CheckBox select;

        ImageView lockImage;

    }

    /**
     * 自定义适配器
     * 
     * @author Administrator
     */
    class MyAdapter extends SimpleAdapter {

        private ArrayList<HashMap<String, Object>> data;

        public MyAdapter(Context context, List<? extends Map<String, Object>> data, int resource,
                String[] from, int[] to) {
            super(context, data, resource, from, to);
            this.data = (ArrayList<HashMap<String, Object>>) data;
            this.resource = resource;

        }

        int resource;

        HashMap<String, Object> map;

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View row = convertView;
            ViewHolder vh = new ViewHolder();
            if (row == null) {
                LayoutInflater inflater = getLayoutInflater();
                row = inflater.inflate(resource, parent, false);
            }
            vh.noteValue = (TextView) row.findViewById(R.id.noteValue);
            vh.select = (CheckBox) row.findViewById(R.id.check);
            vh.lockImage = (ImageView) row.findViewById(R.id.lock);
            map = data.get(position);
            vh.noteValue.setText(map.get(PROJECTION[1]).toString());
            // 要先设置监听器再设置是否选中。
            vh.select.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    String ID = buttonView.getTag().toString();

                    for (HashMap<String, Object> d : data) {
                        if (ID.equals(d.get(PROJECTION[0]).toString())) {
                            d.put("check", isChecked);
                            break;
                        }
                    }
                    checkSelectAll();
                }
            });
            if (Integer.valueOf(map.get(PROJECTION[4]).toString()) == NotePad.DataValue.IS_LOCK) {
                vh.lockImage.setVisibility(View.VISIBLE);
            } else {
                vh.lockImage.setVisibility(View.INVISIBLE);
            }
            vh.select.setTag(map.get(PROJECTION[0]));// 这个要设置在setChecked
                                                     // 和实现这个监听器中用到有关。
            vh.select.setChecked(Boolean.valueOf(map.get("check").toString()));

            vh.select.setFocusable(false);
            row.setTag(vh);
            
            String color = String.valueOf(map.get(PROJECTION[3]));
            Util.setRowColor(color,row);
            return row;
        }

    }

    /*********************************************************************************************************************************************/
    protected static final String[] PROJECTION = new String[] {
            Notes._ID, // 0
            Notes.TITLE, // 1
            Notes.MODIFIED_DATE,// 2
            Notes.COLOR,// 3
            Notes.LOCK
    };

    private static ArrayList<HashMap<String, Object>> data;

    private MyAdapter adapter;

    private CheckBox selectAll;
}
